<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */


class ModcpAction extends HomeAction
{

	public function _initialize()
	{
		parent::_initialize();

		if (!in_array($this->_user['admin_group'], array(1,2,3)))
		{
			$this->error(L('no_mcp_perms'));
		}

		//管理员和超级版主有全局权限,普通版主需获取管辖范围
		$Category = D('Category');
		$where = array();
		if (3 == $this->_user['admin_group'])
		{
			$categories = get_mod_categories($this->_user['user_id']);
			$where['category_id'] = array('in', $categories);
		}

		$cateID = isset($_REQUEST['cid']) ? intval($_REQUEST['cid']) : 0;
		$categoryOptions = $Category->getCategoryOptions($cateID, $where);

		$this->assign('categoryOptions', $categoryOptions);
	}


	public function index()
	{
	    $map = $map2 = $map3 = array();

	    $map['user_group'] = 4;
	    $userCount = M('User')->where($map)->count();
	    
	    if (3 == $this->_user['admin_group'])
	    {
	    	$categories = get_mod_categories($this->_user['user_id']);
	    	$map2['category_id'] = array('in', $categories);
	    	$map3['category_id'] = array('in', $categories);
	    }
	    
	    $map2['status'] = 0;
	    $teamCount = M('Team')->where($map2)->count();

	    $map3['is_visible'] = 0;
	    $questionCount = M('Question')->where($map3)->count();
	    $answerCount = M('Answer')->where($map3)->count();
	    $commentCount = M('Comment')->where($map3)->count();
	   
	    $todo = array(
	       'user_count'     => intval($userCount),
	       'team_count'     => intval($teamCount),
	       'question_count' => intval($questionCount),
	       'answer_count'   => intval($answerCount),
	       'comment_count'  => intval($commentCount),
	    );

		$this->assign('todo', $todo);
	    $this->display();
	}


	//待审核问题,答案,评论队列
	public function moderation()
	{
		
		import('ORG.Util.Page');

		$types = array('team','user','question','answer','comment');
		$type = in_array($_REQUEST['type'], $types) ? $_REQUEST['type'] : 'question';
		$cateIDs = $map = $where = $order = array();
		$parameter = '';

		if ('user' != $type)
		{
		    $cateID = isset($_REQUEST['cid']) ? intval($_REQUEST['cid']) : 0;
    		if ($cateID)
    		{
    			$cateIDs = get_sub_category_ids($cateID, 1);
    	    	$parameter .= '&cid=' .$cateID;
    		}

    		$status = isset($_REQUEST['status']) ? intval($_REQUEST['status']) : 0;
    		$parameter .= '&status='. $status;
		}

		switch (strtolower($type))
		{
			case 'team':
				if ($cateIDs)
				{
					$map['category_id'] = array('in', $cateIDs);
				}
				$map['status'] = $status;
				$View = D('Team');
				break;
				
		    case 'user':
		        $View = $this->_User;
		        $map['user_group'] = 4;
		        break;

			case 'question':
				if ($cateIDs)
				{
					$map['category_id'] = array('in', $cateIDs);
				}
				$map['Question.is_visible'] = $status;
				$View = D('QuestionView');
				break;

			case 'answer':
				if ($cateIDs)
				{
					$map['Answer.category_id'] = array('in', $cateIDs);
				}
				$map['Answer.is_visible'] = $status;
				$View = D('AnswerView');
				break;

			case 'comment':
				if ($cateIDs)
				{
					$map['Comment.category_id'] = array('in', $cateIDs);
				}
			    $map['is_visible'] = $status;
				$View = D('CommentView');
				break;
		}

		$pageSize = 15;
		$total = $View->where($map)->count();
		$Page  = new Page($total, $pageSize);
		$Page->parameter = $parameter;
		$pagination = $Page->show();
		$list = $View->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->assign('type', $type);
		$this->assign('status', $status);
		$this->assign('list', $list);
		$this->assign('pagination', $pagination);
		$this->display();
	}


	//审核团队
	public function approveTeam()
	{
		
		$Team = D('Team');
		
		$mods = $_POST['mods'];

	    if(!$this->_adminGroup['allow_approve_team'])
	    {
	        $this->error(L('no_perms_action'));
	    }
	    
	    if ($this->isPost())
	    {
	    	if (isset($_POST['approve']))
	    	{
	    		$status = 1;
	    		$message = L('team_approved');
	    	}
	    	elseif (isset($_POST['disapprove']))
	    	{
	    		$status = -1;
	    		$message = L('team_disapproved');
	    	}
	    	
	    	if (!empty($mods))
	    	{
		    	foreach ($mods as $mod)
		    	{
		    		$where = array('team_id' => $mod);
		    		$Team->where($where)->setField('status', $status);
		    	}
		    	$this->success($message);
	    	}
	    	else 
	    	{
	    		$this->redirect('Modcp/moderation', array('type'=>'team'));
	    	}
	    }
	}
	
	
	//审核会员
	public function approveUser()
	{
		
		$UserFollow = D('UserFollow');
		
	    $mods = $_POST['mods'];

	    if(!$this->_adminGroup['allow_approve_user'])
	    {
	        $this->error(L('no_perms_action'));
	    }

	    if (empty($mods))
		{
			$this->redirect('Modcp/moderation', array('type' => 'user'));
		}
		else
		{
		    $map = $where = array('user_id' => array('in', $mods));
		    $users = $this->_User->where($map)->select();
		    
		    if (isset($_POST['approve']))
		    {
		        //奖励邀请人以及增加关注
    			foreach ($users as $user)
    			{
    			    if (!empty($user['inviter']))
    			    {
    			        $UserFollow->addFollow($user['user_id'], $user['inviter']);
                        $this->_User->rewardInviter($user['inviter']);
    			    }
    			}
		    	$this->_User->where($where)->setField('user_group', 7);
    		    $message = L('user_approved');
		    }
		    elseif (isset($_POST['disapprove']))
		    {
		        $this->_User->where($where)->setField('user_group', 8); //加入禁止访问用户组
		        $message = L('user_disapproved');
		    }
			$this->success($message);
		}
	}


	//审核问题
	public function approveQuestion()
	{
		
		$Question = D('Question');
		$mods = $_POST['mods'];

		if(!$this->_adminGroup['allow_approve_post'])
	    {
	        $this->error(L('no_perms_action'));
	    }

		if (empty($mods))
		{
			$this->redirect('Modcp/moderation', array('type' => 'question'));
		}
		else
		{
		    if (isset($_POST['approve']))
		    {
    			$data = array(
    		        'expire_time' => time() + 86400 * $this->_global['question_expiration'], //弥补问题过期时间
    		        'is_visible'  => 1,
    		    );
    		    $message = L('question_approved');
		    }
		    elseif (isset($_POST['disapprove']))
		    {
		    	$data = array('is_visible' => -1);
    		    $message = L('question_disapproved');
		    }
		    elseif (isset($_POST['restore']))
		    {
                $message = L('question_restored');
		    }

		    $where = array('question_id' => array('in', $mods));
			$Question->where($where)->save($data);

			//更新分类问题计数

			$this->success($message);
		}
	}


	//审核问题
	public function approveAnswer()
	{
		
	    $Question = D('Question');
		$Answer = D('Answer');

		$questions = $_POST['questions'];
		$mods = $_POST['mods'];

		if(!$this->_adminGroup['allow_approve_post'])
	    {
	        $this->error(L('no_perms_action'));
	    }

        if (!empty($mods))
        {
        	if (isset($_POST['approve']))
		    {
    			$data = array('is_visible' => 1);
    		    $message = L('answer_approved');
		    }
		    elseif (isset($_POST['disapprove']))
		    {
		    	$data = array('is_visible' => -1);
    		    $message = L('answer_disapproved');
		    }
		    elseif (isset($_POST['restore']))
		    {
                $data = array('is_visible' => 1);
                $message = L('answer_restored');
		    }

        	$where = array('answer_id' => array('in', $mods));
        	$Answer->where($where)->save($data);

        	foreach ($mods as $value)
        	{
        		$Question->updateAnswerCount($questions[$value]);
        	}
        	$this->success($message);
        }
        else
        {
            $this->redirect('Modcp/moderation', array('type' => 'answer'));
        }
	}


	//审核评论
	public function approveComment()
	{
		$Comment = D('Comment');
        $mods = $_POST['mods'];
        $relates = $_POST['relates'];

        if(!$this->_adminGroup['allow_approve_post'])
	    {
	        $this->error(L('no_perms_action'));
	    }

        if(!empty($mods))
        {
            $Question = D('Question');
            $Answer = D('Answer');

            if (isset($_POST['approve']))
		    {
    			$data = array('is_visible' => 1);
    		    $message = L('comment_approved');
		    }
		    elseif (isset($_POST['disapprove']))
		    {
		    	$data = array('is_visible' => -1);
    		    $message = L('comment_disapproved');
		    }
		    elseif (isset($_POST['restore']))
		    {
                $data = array('is_visible' => 1);
                $message = L('comment_restored');
		    }

		    $where = array('comment_id' => array('in', $mods));
		    $Comment->where($where)->save($data);

            foreach ($mods as $value)
            {
                $tmp = explode('-', $relates[$value]);
            	if ('Q' == $tmp[0])
            	{
            		$Question->updateCommentCount($tmp[1]);
            	}
            	elseif ('A' == $tmp[0])
            	{
            	    $Answer->updateCommentCount($tmp[1]);
            	}
            }
            $this->success($message);
        }
        else
        {
            $this->redirect('Modcp/moderation', array('type' => 'comment'));
        }
	}


    //审核内容详情
	public function approveDetails()
	{
		
	    $Question = D('Question');
	    $Answer   = D('Answer');
	    $Comment  = D('Comment');

	    $rid = $_GET['rid'];
	    $type = $_GET['type'];
	    $question = $answer = $comment = $answers = $comments = array();

	    switch ($type)
        {
        	case 'question':
        		$question = $Question->find($rid);
        		break;
            case 'answer':
                $answer = $Answer->find($rid);
                $map = array(
                	'question_id' => $answer['question_id'], 
                	'is_visible' => 0,
                );
                $answers = $Answer->where($map)->select();
        		$question = $Question->find($answer['question_id']);
        		break;
        	case 'comment':
        		$comment = $Comment->find($rid);
        		$map = array(
        			'related_id' => $comment['related_id'],
        			'type' => $comment['type'],
        			'is_visible' => 0,
        		);
        		$comments = $Comment->where($map)->select();
        		if ('Q' == $comment['type'])
        		{
        		    $question = $Question->find($comment['related_id']);
        		}elseif ('A' == $comment['type'])
        		{
        		    $answer = $Answer->find($comment['related_id']);
        		}
        		break;
        }

        $this->assign('type', $type);
        $this->assign('question', $question);
        $this->assign('answer', $answer);
        $this->assign('comment', $comment);
        $this->assign('answers', $answers);
        $this->assign('comments', $comments);
        exit($this->fetch());
	}


	//报告相关
	public function report()
	{
		
		$Report = D('Report');

		if ($this->isPost())
		{
		    $mods = $_POST['mods'];
		    if (empty($mods))
		    {
		    	$this->redirect('Modcp/report');
		    }
		    else
		    {
    			$where = array('report_id' => array('in', $mods));
    			if (isset($_POST['close']))
    			{
    				$Report->where($where)->setField('is_closed', 1);
    				$message = L('report_closed');
    			}
    			elseif (isset($_POST['delete']))
    			{
    				$Report->where($where)->delete();
    				$message = L('report_deleted');
    			}
    			$this->success($message);
		    }
		}
		else
		{
		    import('ORG.Util.Page');

    		$map = $order = array();
    		$parameter = '';

    		if (isset($_REQUEST['cid']))
    		{
                $cateIDs = get_sub_category_ids($_REQUEST['cid'], 1);
        		$map['category_id'] = array('in', $cateIDs);
        		$parameter .= '&cid='. $_REQUEST['cid'];
    		}
    		$types = array('open', 'closed');
    		$type = in_array($_REQUEST['type'], $types) ? $_REQUEST['closed'] : 'open';
    		$closed = 'open' == $type ? 0 : 1;
    		$parameter .= '&closed='. $closed;
    		$map['is_closed'] = $closed;

    		$pageSize = 15;
    		$View = D('ReportView');
    		$total = $View->where($map)->count();
    		$Page  = new Page($total, $pageSize);
    		$Page->parameter = $parameter;
    		$pagination = $Page->show();
    		$reports = $View->where($map)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

    		$this->assign('type', $type);
    		$this->assign('reports', $reports);
    		$this->assign('pagination', $pagination);
    		$this->display();
		}
	}


	//禁止相关
	public function banning()
	{
		
		$Blacklist = D('Blacklist');
		
        import('ORG.Util.Page');

	    $types = array('editUser', 'banUser', 'banIP');
	    $type = in_array($_REQUEST['type'], $types) ? $_REQUEST['type'] : 'editUser';
        $pageSize = 15;
	
        if (3 == $this->_user['admin_group'])
        {
        	$map['author_id'] = $this->_user['user_id'];
        }
		if ('editUser' == $type)
		{
			$user = array();
			if ($this->isPost())
			{
				$user = !empty($_POST['user_id']) ? $this->_User->find($_POST['user_id']) : $this->_User->getUserByName($_POST['username']);
	            if (empty($user))
	            {
	            	$this->error(L('user_not_existed'));
	            }	
			}
			$this->assign('user', $user);
		}
        elseif ('banUser' == $type)
        {
            $prefix = C('DB_PREFIX');
            $join = "{$prefix}user ON {$prefix}blacklist.value={$prefix}user.user_id";
            $map = array('type' => 'user_id');
                    
            $total = $Blacklist->where($map)->count();
			$Page = new Page($total, $pageSize);
			$pagination = $Page->show();
            $list = $Blacklist->join($join)->where($map)->select();
        }
        elseif ('banIP' == $type)
        {   
        	$map = array('type' => 'ip');
        	        
	        $total = $Blacklist->where($map)->count();
    		$Page = new Page($total, $pageSize);
    		$pagination = $Page->show();
            $list = $Blacklist->where($map)->select();
        }

        $this->assign('type', $type);
        $this->assign('list', $list);
        $this->assign('pagination', $pagination);
        $this->display();
	}
	
	
		//编辑用户
	public function editUser()
	{
		
		$user = $this->_User->find($_POST['user_id']);
		if (empty($user))
        {
        	$this->error(L('user_not_existed'));
        }
		
		if (!$this->_adminGroup['allow_edit_user'])
		{
			$this->error(L('no_perms_action'));
		}
		
		if ($this->isPost())
		{	
        	$data = array(
            	'website' => trim($_POST['website']),
            	'location' => trim($_POST['location']),
            	'about' => trim($_POST['about']),
            );
            $where = array('user_id' => $user['user_id']);
            $this->_User->where($where)->save($data);
            $this->success(L('user_edited'));
		}
	}
	
	
	//禁止(解禁)用户
	public function banUser()
	{
		
		$Blacklist = D('Blacklist');
		
		if (!$this->_adminGroup['allow_ban_user'])
		{
			$this->error(L('no_perms_action'));
		}
		
		$type = 'user_id';
		if ('include' == $_POST['op'])
		{
			$user = !empty($_POST['user_id']) ? $this->_User->find($_POST['user_id']) : $this->_User->getUserByName($_POST['username']);
            if (empty($user))
            {
            	$this->error(L('user_not_existed'));
            }
            
            $map = array(
            	'type'  => $type, 
            	'value' => $user['user_id'],
            );
            $bannedUser = $Blacklist->where($map)->find();
            if (!empty($bannedUser))
            {
            	$this->error(L('user_banned_already'));
            }
            
            if (in_array($user['user_group'], array(1,2,3)))
            {
            	$this->error(L('no_ban_admin_perms'));
            }
            
            $expiration = !empty($_POST['ban_length']) ? $_POST['ban_length'] * 86400 + time() : 0;
        	$data = array(
        		'type'		  => $type,
        		'value'       => $user['user_id'],
        		'create_time' => time(),
        		'expire_time' => $expiration,
        		'author_id'   => $this->_user['user_id'],
        		'author_name' => $this->_user['username'],
        		'reason'      => $_POST['ban_reason'],
        	);
        	$Blacklist->add($data);
        	
        	$userGroup = ('readonly' == $_POST['ban_type']) ? 5 : 8;
        	$where = array('user_id' => $user['user_id']);
        	$this->_User->where($where)->setField('user_group', $userGroup);
        	
        	$this->success(L('user_banned'));
		}
		elseif ('exclude' == $_POST['op'])
		{
			$mods = $_POST['mods'];
			if (!empty($mods))
			{
				$map = array(
					'type' => $type, 
					'id' => array('in', $mods),
				);
				$results = $Blacklist->where($map)->select();
				foreach ($results as $result)
				{
					$userID = $result['value'];
					$where = array('user_id' => $userID);
					$this->_User->where($where)->setField('user_group', 7);
					$this->_User->autoUpgradeLevel($userID);
				}
				$Blacklist->where($map)->delete();
				$this->assign('jumpUrl', U('Modcp/banning', array('type'=>'banUser')));
				$this->success(L('banlist_updated'));
			}
		}
		$this->redirect('Modcp/banning', array('type'=>'banUser'));
	}
	
	
	//禁止(解禁)IP
	public function banIP()
	{
		
		$Blacklist = D('Blacklist');
		
		if (!$this->_adminGroup['allow_ban_ip'])
        {
        	$this->error(L('no_perms_action'));
        }
        
        $type = 'ip';
        if ('include' == $_POST['op'])
        {
	        $map = array(
	        	'type'  => $type, 
	        	'value' => $_POST['ip'],
	        );
	        $bannedIP = $Blacklist->where($map)->find();
	        if (!empty($bannedIP))
	        {
	        	$this->error(L('ip_banned_already'));
	        }
	        
	        if (!validate_ip($_POST['ip']))
	        {
	        	$this->error(L('ip_invalid'));
	        }
	        
	        $expiration = !empty($_POST['ban_length']) ? $_POST['ban_length'] * 86400 + time() : 0;
        	$data = array(
        		'type'		  => $type,
        		'value'       => trim($_POST['ip']),
        		'create_time' => time(),
        		'expire_time' => $expiration,
        		'author_id'   => $this->_user['user_id'],
        		'author_name' => $this->_user['username'],
        		'reason'      => $_POST['ban_reason'],
        	); 
	        $Blacklist->add($data);
	        $Blacklist->cacheIpBlacklist();
	        $this->success(L('ip_banned'));
		}
		elseif ('exclude' == $_POST['op'])
		{
			$mods = $_POST['mods'];
			if (!empty($mods))
			{
				$map = array(
					'type' => $type, 
					'id' => array('in', $mods),
				);
				$Blacklist->where($map)->delete();
				$Blacklist->cacheIpBlacklist();
				$this->success(L('banlist_updated'));
			}
		}
		$this->redirect('Modcp/banning', array('type' => 'banIP'));
	}

}

/* End of file ModcpAction.class.php */
/* Location: ./App/Lib/Action/Home/ModcpAction.class.php */